<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class model_hutang extends Default_My_Model {

    public function __construct() {
        parent::__construct();
        $this->load->database();
    }

    function getDataHutang($whr, $offset = 0, $length = 30) {
        $sql = "
            SELECT d.*, k.nama, 
            d.nominal_hutang - (select COALESCE(sum(nominal_dibayarkan),0) from pelunasan_hutang where id_hutang = d.id_hutang) as sisa_hutang
            FROM data_hutang d
            left join mt_karyawan k on k.nik = d.nik            
            $whr order by d.is_lunas asc, d.tanggal_hutang LIMIT $length OFFSET $offset";

        return $this->db->query($sql);
    }

    function getDataPelunasan($id_hutang) {
        $sql = "SELECT * from pelunasan_hutang where id_hutang = $id_hutang order by tanggal_pelunasan asc";
        $query = $this->db->query($sql);
        return $query->result();
    }

    function deleteHutang($id) {
        $this->db->where('id_hutang', $id);
        $this->db->delete('data_hutang', $where);

        $this->db->where('id_hutang', $id);
        $this->db->delete('pelunasan_hutang', $where);
    }

    function deletePelunasan($id) {
        $this->db->where('id_pelunasan', $id);
        $this->db->delete('pelunasan_hutang');
    }

    function insertUpdateHutang($data, $id_hutang = "") {
        $set = array(
            "catatan" => $data["catatan"],
            "jumlah_cicilan" => $data["jumlah_cicilan"],
            "nominal_hutang" => $data["nominal_hutang"],
            "tanggal_jatuh_tempo" => $data["tanggal_jatuh_tempo"],
            "tanggal_hutang" => $data["tanggal_hutang"],
            "nik" => $data["nik"]
        );
        if ($id_hutang == "") {
            $this->db->insert("data_hutang", $set);
            return $this->db->insert_id();
        } else {
            $this->db->update("data_hutang", $set, "id_hutang = " . $id_hutang);
        }
    }

    function insertPelunasan($data) {
        $this->db->insert("pelunasan_hutang", $data);
        return $this->db->insert_id();
    }

}

?>